package rttest;

public class RTTest extends RealtimeThread {

	public static final int THREADS = 5;
	
	private int threadID;
	private boolean running = true;
	private int count = 0;
	
	public RTTest(int id)
	{
		super();
		threadID = id;
	}
	@Override
	public void run()
	{
		System.out.println("RTThread " + threadID + ", pid: " + getTID());
		while(running)
		{
			System.out.println("" + threadID + "thread: " + ++count + " iteration");
			for(int i = 0; i < Integer.MAX_VALUE; i++) for(int j = 0; j < Integer.MAX_VALUE; j++) ;
			waitForNextPeriod();
		}
	}
	public static boolean waitForNextPeriod()
	{
		try {
			sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return true;
	}
	public void setThreadID(int id)
	{
		threadID = id;
	}
	public void stopThread()
	{
		running = false;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("Beginning of program");

		int tid = NativeHelper.gettid();
		System.out.println("Parent tid : " + tid + "\n");
		
		RTTest[] threads = new RTTest[5];
		for(int i = 0; i < THREADS; i++)
		{
			threads[i] = new RTTest(i);
		}
		for(int i = 0; i < THREADS; i++)
		{
			System.out.println("Starting thread " + i);
			threads[i].start();
		}
		
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		System.out.println("Cyclic preemption through thread 0 to " + THREADS + ":");
		for(int i = 0; i < THREADS; i++)
		{
			;
		}
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		
		for(int i = 0; i < THREADS; i++)
		{
			System.out.println("Stopping thread " + i);
			threads[i].stopThread();
		}
		for(int i = 0; i < THREADS; i++)
		{
			try {
				threads[i].join();
			} catch (InterruptedException e) {
				System.out.println("Join error with thread " + i);
				e.printStackTrace();
			}
		}
		
		System.out.println("End of program");
	}
}
